package com.cskaoyan.javase.oop3._1interface._4example.operation.dao.impl;

import com.cskaoyan.javase.oop3._1interface._4example.model.Goods;
import com.cskaoyan.javase.oop3._1interface._4example.model.GoodsData;
import com.cskaoyan.javase.oop3._1interface._4example.operation.dao.IGoodsDao;

/**
 * 实现商品数据处理的类
 *
 * @since 11:24
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class IGoodsDaoImpl implements IGoodsDao {
    // 要完成数据处理,需要依赖于数据源
    private Goods[] goods = GoodsData.GOODS;

    /**
     * 做数据处理,只返回真实对象数组,相当于去除null元素
     * @return com.cskaoyan.javase.oop3._1interface._4example.model.Goods[]
     * @author wuguidong@cskaoyan.onaliyun.com
     * @since 2022/05/20 11:30
     */
    @Override
    public Goods[] getRealGoods() {
        // 1.创建新数组
        int count = 0;
        for (Goods good : goods) {
            if (good == null) {
                count++;
            }
        }
        Goods[] result = new Goods[goods.length - count];
        // 2.给新数组赋值
        int newIndex = 0;
        for (Goods good : goods) {
            if (good != null) {
                result[newIndex] = good;
                newIndex++;
            }
        }
        return result;
    }

    /**
     * 在原始数组,数据源数组中新增一条商品信息
     * @param goodsInsert
     * @return int
     * @author wuguidong@cskaoyan.onaliyun.com
     * @since 2022/05/20 11:42
     */
    @Override
    public int createGoods(Goods goodsInsert) {
        // 1.首先做id校验
        int idInsert = goodsInsert.getId();
        for (Goods realGood : getRealGoods()) {
            if (realGood.getId() == idInsert) {
                // id重复
                return 1;
            }
        }
        // 代码运行到这里,id一定不重复,尝试插入
        for (int i = 0; i < goods.length; i++) {
            // 查找null的位置,然后赋值
            if (goods[i] == null) {
                goods[i] = goodsInsert;
                return 3;
            }
        }
        // 遍历完整个数组,都没有插入成功,数组满了
        return 2;
    }

    /**
     * 根据传入的id 删除一条商品信息
     * @param id
     * @return boolean
     * @author wuguidong@cskaoyan.onaliyun.com
     * @since 2022/05/20 14:29
     */
    @Override
    public boolean deleteGoods(int id) {
        for (int i = 0; i < goods.length; i++) {
            if (goods[i] == null){
                continue;
            }
            if (goods[i].getId() == id) {
                // 找到了目标商品
                goods[i] = null;
                return true;
            }
        }
        return false;
    }

}
